package cn.chencaiju.blog.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.chencaiju.blog.domain.AjaxResponse;
import cn.chencaiju.blog.domain.Category;
import cn.chencaiju.blog.domain.Post;
import cn.chencaiju.blog.mapper.PostMapper;

public class PostService {
	private PostMapper mapper=null;
	
	public AjaxResponse<Post> page(){
		List<Post> list = mapper.selectAll();
		int count = mapper.count();
		AjaxResponse<Post> ajax=new AjaxResponse<>();
		ajax.setData(list);
		ajax.setCount(count);
		ajax.setCode(0);
		ajax.setMsg("successed");

		return ajax;
	}
	public AjaxResponse<Post> page(String pages, String limit) {
		if(limit==null||limit=="") return null;
		if(pages==null||pages=="")return null;
		int size=Integer.valueOf(limit);
		int start=(Integer.valueOf(pages)- 1) * size;
		return page(start,size);
	}
	private AjaxResponse<Post> page(int pages, int limit) {
		List<Post> list = mapper.page(pages,limit);
		System.out.println(list.get(0).getCategory());
		int count=mapper.count();
		AjaxResponse<Post> response=new AjaxResponse<>();
		response.setCode(0);
		response.setCount(count);
		response.setData(list);
		response.setMsg("successed");
		return response;
	}
	public int deleteBatch(String[] ids) {
		return mapper.deleteBatch(ids);		
	}
	public int insert(String title, String cid, String content,String created) {
		if(cid==null||cid=="")return -1;
		Post p=new Post();
		Category cate=new Category();
		cate.setId(Integer.valueOf(cid));
		p.setCategory(cate);
		p.setContent(content);
		p.setTitle(title);
		Date date=new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			date = sdf.parse(created);
			p.setCreated(date);
			return mapper.insert(p);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return -1;
	}
	public List<Post> search(String title, String cid, String created) {
		return mapper.search(title, cid, created);
		
	}
	public int count() {
		return mapper.count();
		
	}
}
